#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>

class Sock
{
public:
    static int Socket()
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if(sock < 0)
        {
            std::cerr << "Socket error" << errno << std::endl;
            exit(2);
        }
        return sock;
    }

    static void Bind(int sock, u_int16_t port)
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(port);

        if(bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            std::cerr << "Bind error" << errno << std::endl;
            exit(3);
        }
    }

    static void Listen(int sock)
    {
        if(listen(sock, 5) < 0)
        {
            std::cerr << "Listen error" << errno << std::endl;
            exit(4);
        }
    }

    static int Accept(int sock)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int fd = accept(sock, (struct sockaddr*)&peer, &len);
        if(fd >= 0)
        {
            return fd;
        }
        return -1;
    }

    static void Connect(int sock, std::string server_ip, uint16_t port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(sockaddr_in));
        peer.sin_family = AF_INET;
        peer.sin_addr.s_addr = inet_addr(server_ip.c_str());
        peer.sin_port = htons(port);
        
        if(connect(sock, (struct sockaddr*)&peer, sizeof(peer)) < 0)
        {
            std::cerr << "connet failed" << errno << std::endl;
            exit(5);
        }
    }
};
